//
//  RTLocationManager.m
//  AiFang
//
//  Created by zheng yan on 12-4-24.
//  Copyright (c) 2012年 anjuke. All rights reserved.
//

#import "WSLocationManager.h"
#import "UIComponent.h"

static NSString * const kSelectedCityName = @"selectedCityName";

@interface WSLocationManager ()

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) NSString *locatedCityName;

@end

@implementation WSLocationManager
@synthesize locationManager  = _locationManager;
@synthesize userLocation     = _userLocation;
@synthesize locatedCityName  = _locatedCityName;
@synthesize selectedCityName = _selectedCityName;

+ (instancetype)sharedInstance
{
    static dispatch_once_t pred;
    static WSLocationManager *sharedInstance = nil;
    dispatch_once(&pred, ^{
        sharedInstance = [[WSLocationManager alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.distanceFilter = 500;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]){
            [self.locationManager requestWhenInUseAuthorization];
            [self.locationManager requestAlwaysAuthorization];
        }
        self.locatedCityName = nil;
        NSString *selectedCityName = [[NSUserDefaults standardUserDefaults] stringForKey:kSelectedCityName];
        if (![selectedCityName length]) {
            [self setSelectedCityName:@"上海"];
        }
    }
    
    return self;
}

- (CLLocation *)userLocation
{
    if (self.locationManager.location == nil) {
        [self restartLocation];
    }
    return self.locationManager.location;
}

- (BOOL)locationServicesEnabled
{
    return [CLLocationManager locationServicesEnabled];
}

- (WSCLServiceStatus)locationServicesStatus
{
    WSCLServiceStatus status = RTCLServiceStatusUnknowError;
    BOOL serviceEnable = [CLLocationManager locationServicesEnabled];
    if (serviceEnable) {
        if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"4.2")) {
            CLAuthorizationStatus authorizationStatus = [CLLocationManager authorizationStatus];
            switch (authorizationStatus) {
                case kCLAuthorizationStatusNotDetermined:
                    status = RTCLServiceStatusFirst;
                    break;
                case kCLAuthorizationStatusAuthorizedAlways:
                    status = RTCLServiceStatusOK;
                    break;
                case kCLAuthorizationStatusDenied:
                    status = RTCLServiceStatusDenied;
                    break;
                default:
                    break;
            }
        }
    }else {
        status = RTCLServiceStatusDenied;
    }
    return status;
}

- (void)setSelectedCityName:(NSString *)selectedCityName
{
    NSString *tmp = [[NSUserDefaults standardUserDefaults] stringForKey:kSelectedCityName];
    if (![tmp isEqualToString:selectedCityName]) {
        [[NSUserDefaults standardUserDefaults] setObject:selectedCityName forKey:kSelectedCityName];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [[NSNotificationCenter defaultCenter] postNotificationName:WSSelectedCityNameChangedNotification object:nil userInfo:nil];
    }
}

- (NSString *)selectedCityName
{
    return [[NSUserDefaults standardUserDefaults] stringForKey:kSelectedCityName];
}

- (void)restartLocation
{
    if ([self locationServicesEnabled]) {
        [self.locationManager stopUpdatingLocation];
        [self.locationManager startUpdatingLocation];
    }
}

- (void)startLocation
{
    if ([self locationServicesEnabled]) {
        [self.locationManager startUpdatingLocation];
    }    
}

- (void)stopLocation
{
    if ([self locationServicesEnabled]) {
        [self.locationManager stopUpdatingLocation];
    }        
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    [self fetchCityInfoWithLocation:newLocation];
}


- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    if (self.locatedCityName != nil) {
        self.locatedCityName = nil;
        [[NSNotificationCenter defaultCenter] postNotificationName:WSLocatedCityNameChangedNotification object:nil userInfo:nil];
    }
}

#pragma mark - Update GPS city
- (void)fetchCityInfoWithLocation:(CLLocation *)location
{
    CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
    [geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray *placeMarkArray, NSError *error){
        CLPlacemark *placemark = [placeMarkArray lastObject];
        if (placemark) {
            //NSString *cityName = nil;
            NSDictionary *addressDictionary = placemark.addressDictionary;
            for (NSString *key in addressDictionary.allKeys) {
                
                if ([key isEqualToString:@"City"]) {
                    NSString *completeCityName = addressDictionary[@"City"];
                    //上海市 => 上海
                    NSString *cityName = [completeCityName substringToIndex:(completeCityName.length - 1)];
                    if (![self.locatedCityName isEqualToString:cityName]) {
                        self.locatedCityName = cityName;
                        [[NSNotificationCenter defaultCenter] postNotificationName:WSLocatedCityNameChangedNotification object:nil userInfo:nil];
                    }
                    break;
                }
                
                if ([key isEqualToString:@"State"]) {
                    //上海市只在"State"中出现，有可能直辖市都只是在State中出现。
                    NSString *completeCityName = addressDictionary[@"State"];
                    //要检查一下这个state是不是包含“市”这个字，因为也有可能是江苏省。
                    NSRange range = [completeCityName rangeOfString:@"市"];
                    if (range.location != NSNotFound) {
                        NSString *cityName = [completeCityName substringToIndex:(completeCityName.length - 1)];
                        if (![self.locatedCityName isEqualToString:cityName]) {
                            self.locatedCityName = cityName;
                            [[NSNotificationCenter defaultCenter] postNotificationName:WSLocatedCityNameChangedNotification object:nil userInfo:nil];
                        }
                        break;
                    }
                }
            }
        }
    }];
}

@end
